#include "DxyThreadPool.h"


namespace dxy::threadPool
{


DxyThreadPool::DxyThreadPool()
{

}

DxyThreadPool::~DxyThreadPool()
{
    
}

void DxyThreadPool::start(int num)
{
    m_threadNum = num;
    for(int i = 0; i < m_threadNum; i++)
    {
        m_threads.push_back(std::make_unique<std::thread>(&DxyThreadPool::work, this));
        m_threads[i]->detach();
    }
}

void DxyThreadPool::stop()
{
    m_isStop = true;
    m_cond.notify_all();
}

void DxyThreadPool::work()
{
    while(1)
    {
        std::unique_lock<std::mutex> lk(m_mtx);
        m_cond.wait(lk, [this] () {
            if(this->m_tasks.size() == 0 && this->m_isStop == false)
            {
                return false;
            }
            return true;
        });
        lk.unlock();
        if(m_isStop == true) return;
        auto task = m_tasks.frontAndPop();
        task();
    }
}



}
